//
//  BinDingPhoneViC.m
//  ZhiBoYuan
//
//  Created by apple on 2018/5/25.
//  Copyright © 2018年 apple. All rights reserved.
//

#import "BinDingPhoneViC.h"

#import "TabVC.h"

#import "TeaterRegistViewController.h"

@interface BinDingPhoneViC ()

@property(nonatomic,strong)UITextField *Phone;

@property(nonatomic,strong)UITextField *number;

@property(nonatomic,strong)UIButton *getNumber;

@property(nonatomic,strong)UIButton *sendButton;

@property(nonatomic,assign)NSInteger shijian;

@property(nonatomic,strong)NSTimer *timer;


@property(nonatomic,strong)UILabel *phoneLable;
@property(nonatomic,strong)UILabel *numberLabel;

@end

@implementation BinDingPhoneViC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    self.title = @"绑定手机";
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.Phone];
    
    [self.view addSubview:self.number];
    
    [self.view addSubview:self.sendButton];
    
    
    NSLog(@" _openid = %@  type= %@",_openid,_type);
    
    self.Phone.sd_layout
    .topSpaceToView(self.view, NAVIGATION_BAR_HEIGHT + 60)
    .leftSpaceToView(self.view, 50)
    .rightSpaceToView(self.view, 50)
    .heightIs(40);
    
    self.number.sd_layout
    .topSpaceToView(self.Phone, 30)
    .leftSpaceToView(self.view, 50)
    .rightSpaceToView(self.view, 50)
    .heightIs(40);
    
    self.sendButton.sd_layout
    .topSpaceToView(self.number, 30)
    .leftSpaceToView(self.view, 50)
    .rightSpaceToView(self.view, 50)
    .heightIs(40);
    
}

#pragma mark ----------------------- 发验证码 ------------------------
-(void)sendMessage:(UIButton *)sender
{
    
    SGParameter *parameter  = [[SGParameter alloc] init];
    
    parameter.body          = @{@"phone":_Phone.text,
                                @"type":@"oauthsLogin"
                                };
    
    NSString *lastUrl       = @"g=Client&m=Register&a=getSmsCode";
    
        __weak __typeof(&*self)weakSelf = self;
    
    [SGHttpTool POST:[NSString stringWithFormat:@"%@%@",HTTPP,lastUrl] parameter:parameter sucess:^(id responseObject) {
        
        NSDictionary *dic = responseObject;
        
        NNSLog(@"%@",dic);
        
        if ([dic[@"status"] integerValue] == 200)
        {
            NSLog(@"发验证码");
            weakSelf.shijian = 60;
            weakSelf.timer =  [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(openTimer) userInfo:nil repeats:YES];
            [weakSelf.timer fire];
            weakSelf.getNumber.enabled = NO;
            
        }else{
            
        }
        [MBProgressHUD showTextOnly:self.view message:dic[@"msg"] delay:3];

        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        
    }];
    
}


#pragma mark -----------------------  验证  ------------------------
-(void)okSender:(UIButton *)sender
{
    
    [self.view endEditing:YES];
    // 验证验证码
    NSLog(@"绑定");
    
    SGParameter *parameter  = [[SGParameter alloc] init];

    parameter.body          = @{
                                @"phone":_Phone.text,
                                @"sms_code":_number.text
                                };
    NSString *lastUrl  =  @"g=Client&m=Login&a=checkCode";
    
    NSString *url      = [NSString stringWithFormat:@"%@%@",HTTPP,lastUrl] ;
     __weak __typeof(&*self)weakSelf = self;
    [SGHttpTool POST:url parameter:parameter sucess:^(id responseObject) {

        NSDictionary *dic = responseObject;

        NNSLog(@"%@",dic);
        
        
        if ([dic[@"status"] integerValue] == 501) {
             [MBProgressHUD showTextOnly:self.view message:dic[@"msg"] delay:3];
        }else{
            [weakSelf bingding];
        }


        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);

    }];
    
}


#pragma mark ----------------------- 绑定 ------------------------
- (void)bingding{
    
    
    SGParameter *parameter  = [[SGParameter alloc] init];
    
    NSString *NewOpenid = [NSString stringWithFormat:@"%@1",self.openid];
    
    parameter.body  = @{
                        @"openid":NewOpenid,
                        @"type":_type,
                        @"phone":_Phone.text
                        };
    
    NSString *lastUrl  =  @"g=Client&m=Login&a=oauths";
    NSString *url      = [NSString stringWithFormat:@"%@%@",HTTPP,lastUrl] ;
    __weak __typeof(&*self)weakSelf = self;
    [SGHttpTool POST:url parameter:parameter sucess:^(id responseObject) {
        
        NSDictionary *dic = responseObject;
        
        NSLog(@"登录结果 %@",dic);
        [weakSelf enterMainPage:dic];
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
        
    }];
    
    
}


#pragma mark ----------------------- 进入主页 ------------------------
-(void)enterMainPage:(NSDictionary *)dic{
    
    
    if ([dic[@"status"] intValue] == 200) {
        [MBProgressHUD showTextOnly:self.view message:@"登录成功" delay:3.0f];
        
        UserinfoModel *model = [UserinfoModel mj_objectWithKeyValues:dic[@"data"][@"user_info"]];
        model.isLogIn = @"loginIn";
        [ZYUserManager saveUserInfo:model];
        NSLog(@"%@",[ZYUserManager userInfo].small_img);
        
        if ([[ZYUserManager userInfo].type integerValue] == 2 ) {
            ((AppDelegate *)[UIApplication sharedApplication].delegate).teacher = YES;
        }else{
            ((AppDelegate *)[UIApplication sharedApplication].delegate).teacher = NO;
        }

        TabVC * vc = [[TabVC alloc]init];
        self.view.window.rootViewController = vc;
        
        
        
    }else if ([dic[@"status"] intValue] == 202){
        UserinfoModel *model = [ZYUserManager userInfo];
        
        model = [UserinfoModel mj_objectWithKeyValues:dic[@"data"][@"user_info"]];
        [ZYUserManager saveUserInfo:model];
        //            [MBProgressHUD showTextOnly:self.view message:dic[@"msg"] delay:2.0f];
        
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:dic[@"msg"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil, nil];
        [alertView show];
        
        TeaterRegistViewController *teacherRVC = [[TeaterRegistViewController alloc]init];
        [self.navigationController pushViewController:teacherRVC animated:YES];
        
    }else if ([dic[@"status"] intValue] == 203){
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"认证审核中，请耐心等待，审核通过后方可登陆" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil, nil];
        [alertView show];
        
    }else if ([dic[@"status"] intValue] == 501){
        NSLog(@"绑定手机📱📱");
        
        if ([self string:dic[@"msg"] subStr:@"手机号未注"]) {
            
            NSLog(@"未注册");
            
            
//            15210535966  //036171
            
            [self showOkayCancelAlertTitle:dic[@"msg"] message:@"去注册？"];
            
            
        }else{
            [MBProgressHUD showTextOnly:self.view message:dic[@"msg"] delay:2.0f];

            
        }
        
        

        
        
    }else{
        [MBProgressHUD showTextOnly:self.view message:dic[@"msg"] delay:2.0f];
    }
}



- (void)showOkayCancelAlertTitle:(NSString *)title  message:(NSString *)message {
    
    NSString *cancelButtonTitle = NSLocalizedString(@"取消", nil);
    
    NSString *otherButtonTitle = NSLocalizedString(@"确认", nil);
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:cancelButtonTitle style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        
        NSLog(@"取消");
        
    }];
    
    UIAlertAction *otherAction = [UIAlertAction actionWithTitle:otherButtonTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        
        NSLog(@"确认");
        
//        [self.navigationController popViewControllerAnimated:YES];
        
        if (self.binding)
        {
            self.binding(YES);
            
            
        }
        
    }];
    
    [alertController addAction:cancelAction];
    
    [alertController addAction:otherAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
    
}

-(BOOL)string:(NSString *)str subStr:(NSString *)subStr{
    
    if([str rangeOfString:subStr].location !=NSNotFound)
        
    {
        NSLog(@"包含");
        return YES;
    }
    
    else
        
    {
        
        NSLog(@"不包含");
        return NO;
        
    }

}



//-----------------

-(void)openTimer
{
    NSString *str = @"获取验证码";
    if (_shijian == 0)
    {
        [self.timer invalidate];
        self.getNumber.enabled = YES;
    }
    else
    {
        self.getNumber.enabled = NO;
        str = [NSString stringWithFormat:@"倒计时 %zd 秒",_shijian];
    }
    [self.getNumber setTitle:str forState:(UIControlStateNormal)];
    _shijian--;
}

-(UIButton *)getNumber
{
    if (!_getNumber)
    {
        _getNumber = [UIButton buttonWithType:(UIButtonTypeCustom)];
        _getNumber.frame = CGRectMake(10, 0, 120, 40);
        [_getNumber setTitleColor:[UIColor blueColor] forState:(UIControlStateNormal)];
        [_getNumber setTitleColor:[UIColor redColor] forState:(UIControlStateDisabled)];
        [_getNumber setTitle:@"获取验证码" forState:(UIControlStateNormal)];
        [_getNumber addTarget:self action:@selector(sendMessage:) forControlEvents:(UIControlEventTouchUpInside)];
        
    }
    return _getNumber;
}

-(UIButton *)sendButton{
    if (!_sendButton) {
        _sendButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
        _sendButton.frame = CGRectMake(10, 0, 120, 40);
        
        
        [_sendButton setTitleColor:[UIColor whiteColor] forState:(UIControlStateSelected)];
        
        [_sendButton setTitle:@"绑 定" forState:(UIControlStateNormal)];
        
        
        [_sendButton addTarget:self action:@selector(okSender:) forControlEvents:(UIControlEventTouchUpInside)];
        
        
        _sendButton.titleLabel.font = [UIFont systemFontOfSize:16];
        
        _sendButton.backgroundColor = ZhuTiColor;
        
        
        _sendButton.layer.masksToBounds = YES;
        _sendButton.layer.cornerRadius  =  40/2;
    }
    return _sendButton;
}


-(UITextField *)Phone{
    if (!_Phone)
    {
        _Phone = [UITextField new];
        
        _Phone.placeholder = @"请输入手机号";
        
        [_Phone setBorderStyle:(UITextBorderStyleLine)];
        
        
        _Phone.layer.masksToBounds = YES;
        _Phone.layer.cornerRadius = 40/2;
        _Phone.layer.borderWidth = 1;
        _Phone.layer.borderColor = hui1Color.CGColor;
        
        _Phone.leftView = self.phoneLable;
        
        [_Phone setLeftViewMode:(UITextFieldViewModeAlways)];
        
        [_Phone setKeyboardType:(UIKeyboardTypeNumberPad)];
        
    }
    return _Phone;
}


-(UILabel *)phoneLable{
    if (!_phoneLable) {
        _phoneLable = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 30, 40)];
        _phoneLable.text = @" ";
    }
    return _phoneLable;
}

-(UITextField *)number{
    if (!_number)
    {
        _number = [UITextField new];
        
        _number.placeholder = @"请输入短信验证码";
        
        [_number setBorderStyle:(UITextBorderStyleNone)];
        
        _number.rightView = self.getNumber;
        _number.layer.masksToBounds = YES;
        _number.layer.cornerRadius = 40/2;
        _number.layer.borderWidth = 1;
        _number.layer.borderColor = hui1Color.CGColor;

        _number.rightViewMode = UITextFieldViewModeAlways;
        _number.leftView = self.numberLabel;
        
        
        _number.leftViewMode = UITextFieldViewModeAlways;
        
        [_number setKeyboardType:(UIKeyboardTypeNumberPad)];
    }
    return _number;
}

-(UILabel *)numberLabel{
    if (!_numberLabel) {
        _numberLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 30, 40)];
        _numberLabel.text = @" ";
    }
    return _numberLabel;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
